/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gcalscraper.wapo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author dave
 */
public class Data implements DetailWorkerListener, PageWorkerListener {

  private List<Event> events;
  
  private Set<Integer> finishedPages;
  private List<Integer> pageWorkQueue;
  private List<Event> detailWorkQueue;
  
  private PageWorker[] pageWorkerPool;
  private DetailWorker[] detailWorkerPool;
  
  private int detailWorkersCount;
  private int pageWorkersCount;
  
  private boolean done;
  
  public Data() {
    events = Collections.synchronizedList(new ArrayList<Event>());
  }
  
  public void load() {
    
    finishedPages = Collections.synchronizedSet(new HashSet<Integer>());
    pageWorkQueue = Collections.synchronizedList(new ArrayList<Integer>());
    
    synchronized(pageWorkQueue) {
      pageWorkQueue.add(new Integer(1));
    }
    
    detailWorkQueue = Collections.synchronizedList(new ArrayList<Event>());
    
    pageWorkerPool = new PageWorker[10];
    for (int i = 0; i < pageWorkerPool.length; i++) {
      pageWorkerPool[i] = new PageWorker(          
          pageWorkQueue, 
          events,
          finishedPages, 
          detailWorkQueue, this);
      pageWorkerPool[i].start();
    }
    
    detailWorkerPool = new DetailWorker[10];
    for (int i = 0; i < detailWorkerPool.length; i++) {
      detailWorkerPool[i] = new DetailWorker(detailWorkQueue, this);
      detailWorkerPool[i].start();
    }
    
    while (!done) {
      try {
        Thread.sleep(1000);
      } catch (Exception ex) {
      }
    }    
  }

  public List<Event> getEvents() {
    return events;
  }

  public synchronized void startDetail(Event e) {
    detailWorkersCount++;
  }

  public synchronized void stopDetail(Event e) {
    detailWorkersCount--;
    doneCheck();
  }

  public synchronized void startPage(Integer i) {
    pageWorkersCount++;
    
  }

  public synchronized void stopPage(Integer i) {
    pageWorkersCount--;
    doneCheck();
  }
  
  public void doneCheck() {
    boolean finished = false;
    if (pageWorkersCount <= 0 && detailWorkersCount <= 0) {
      synchronized(pageWorkQueue) {
        synchronized(detailWorkQueue) {
          if (pageWorkQueue.size() <= 0 && detailWorkQueue.size() <= 0) {
            finished = true;
            for (int i = 0; i < pageWorkerPool.length; i++) {
              pageWorkerPool[i].setDone(true);
            }
            for (int i = 0; i < detailWorkerPool.length; i++) {
              detailWorkerPool[i].setDone(true);
            }
            pageWorkQueue.notifyAll();
            detailWorkQueue.notifyAll();
          }
        }
      }
    }
    
    if (finished)
      done = true;
  }
}
